<template>
  <el-dialog
    v-dialogDrag
    :visible="popupsVisible"
    width="70%"
    :append-to-body="true"
    :close-on-click-modal="false"
    @close="closeEdit"
  >
    <dialogHeader
      slot="title"
      :title="titleName"
      :style-type="$store.state.app.dialogType"
    />
    <!-- 显示按钮的onetabel -->
    <one-table-template
      ref="multipleTable"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-is-show-select="true"
      :dynamic-is-init-table="true"
      :dynamic-form-fields="formField"
      :dynamic-is-show-more-btn="false"
      :callback-obj="callbackObjAdd"
    />
  </el-dialog>
</template>

<script>
import dialogHeader from '@/components/dialogHeader'
import OneTableTemplate from '@/components/templates/oneTable'
import { oneTableTemplateMixins } from '@/components/mixins/oneTableTemplateMixins'
import request from '@/utils/request'
import api from '@/api/pa/apiBranchWarehouse'
import { exportExcel } from '@/utils/getTimeString.js'
import orApi from '@/api/pa/apiBaseData'
export default {
  components: {
    dialogHeader,
    OneTableTemplate
  },
  mixins: [oneTableTemplateMixins],
  props: {
    popupsVisible: {
      type: Boolean,
      default: false
    },
    dataForForm: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      editPopupsVisible: false,
      titleName: '新建盘点单',
      // 网格查询API配置对象
      apiConfig: api.findDlrStorageInfo,
      selectiondata: [],
      // 动态组件-按钮
      tableButtons:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          : [
            {
              compKey: 'btnKey1',
              type: 'primary',
              size: 'small',
              name: 'search',
              clickEvent: () => this.$refs['multipleTable'].queryTable(),
              // clickEvent: () => this.queryTable('', '', '', '', (response) => {
              //   this.$refs['multipleTable'].list = response.rows
              // }),
              text: this.$t('sys.button.query'), // 查询
              position: 'right',
              fuzzySearch: true
            },
            {
              compKey: 'btnKey2',
              type: '',
              size: 'small',
              name: 'reset',
              clickEvent: () => this.reset(),
              text: this.$t('sys.button.reset'),
              position: 'right' // 重置
            },
            {
              compKey: 'btnKey1',
              type: '',
              size: 'small',
              name: '',
              clickEvent: () => this.pass(),
              text: '开始',
              position: 'left'
            },
            {
              compKey: 'btnKey1',
              type: '',
              size: 'small',
              name: '',
              clickEvent: () => this.deleteTable(),
              text: this.$t('sys.button.delete'),
              position: 'left'
            },
            {
              compKey: 'btnKey7',
              type: '',
              size: 'small',
              name: 'importTemplate',
              position: 'upload',
              clickEvent: () => this.handFileListChange(),
              text: '导入'
            },
            {
              compKey: 'btnKey9',
              type: '',
              size: 'small',
              clickEvent: () => this.exportExcel111(),
              text: '导出',
              name: 'export',
              position: 'left'
            },
            {
              compKey: 'btnKey8',
              type: 'text',
              size: 'small',
              name: '',
              position: 'upload',
              click: (event) => {
                this.templateDownload()
              }
            }
          ],
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '盘点方式：',
              codeField: 'checkModel',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              options: [
                { statusId: '2', statusText: '抽盘' },
                { statusId: '1', statusText: '全盘' }
              ],
              clearable: false,
              type: 'dropdownList',
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey2',
              labelName: '仓库名称：',
              codeField: 'warehouseId',
              textField: 'warehouseName',
              customObj: {
                api: {
                  APIUrl: 'mp/e3sh/spareparts/nodestorehouse/dlrPartWarehouseMaintainService/queryOtherOutboundApplicationInfo.do'
                },
                defOptionFields: ['warehouseId', 'warehouseName']
              },
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey3',
              labelName: '仓库编码：',
              codeField: 'storageLocation',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              disabled: false,
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey4',
              labelName: '出库日期：',
              codeField: 'beginDate,endDate',
              component: () =>
                import('@/components/org/datePicker/andtDatePicker'),
              type: 'YYYY-MM-DD',
              format: 'yyyy-MM-dd',
              disabled: false,
              isMust: true
            },
            {
              compKey: 'compKey5',
              labelName: '出库类型：',
              codeField: 'billType',
              disabled: false,
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              options: [
                { statusId: '1', statusText: '维修出库' },
                { statusId: '3', statusText: '网点销售出库' },
                { statusId: '4', statusText: '内部领用出库' },
                { statusId: '6', statusText: '备件报废出库' },
                { statusId: '8', statusText: '备件盘亏出库' },
                { statusId: '110', statusText: '采购销退出库' },
                { statusId: '111', statusText: '呆滞件销退出库' }
              ],
              type: 'dropdownList',
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey6',
              labelName: '备件编码：',
              codeField: 'partNo',
              disabled: false,
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              disabled: false,
              span: 6
            },
            {
              compKey: 'compKey7',
              labelName: '备件名称：',
              codeField: 'partName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              disabled: false,
              span: 6
            },
            {
              compKey: 'compKey8',
              labelName: '维修类型：',
              codeField: 'partRepairType',
              textField: 'partRepairTypeName',
              disabled: false,
              customObj: {
                api: orApi.queryPartRepairs
              },
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey9',
              labelName: '过滤零库存备件',
              codeField: 'accountQty',
              // lookuptype: "VE0212",
              disabled: false,
              component: () => import('@/components/org/checkBox'),
              type: 'inputText',
              isMust: true,
              span: 8
            }
          ],
      callbackObjAdd: {
        // 手动勾选时
        onCheckSelect: (selection, row) => {
          this.selectiondata = selection
        }
        // 查询成功后回调
        // onQueryReturn: (response) => {
        //   this.onQueryReturn(response)
        // }
      },
      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'partId',
              label: '备件ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'dlrId',
              label: '网点ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'warehouseId',
              label: '仓库ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'partNo',
              label: '备件编码'
            },
            {
              prop: 'partName',
              label: '备件名称'
            },

            {
              prop: 'unit',
              label: '单位'
            },
            {
              prop: 'warehouseName',
              label: '仓库名称',
              width: '150px'
            },
            {
              prop: 'storageLocation',
              label: '仓位编码'
            },
            {
              prop: 'accountQty',
              label: '账面数量'
            },
            {
              prop: 'partRepairTypeCn',
              label: '备件维修类型'
            }
          ],

      formField: {
        checkModel: '2',
        warehouseId: '',
        storageLocation: '',
        beginDate: '',
        endDate: '',
        partNo: '',
        partName: '',
        partRepairType: '',
        billType: '',
        accountQty: '0'
      }
    }
  },

  watch: {
    'formField.checkModel': {
      deep: true,
      handler: function(newV, oldV) {
        if (newV == '1') {
          this.tableComponents[2].disabled = true
          this.tableComponents[3].disabled = true
          this.tableComponents[4].disabled = true
          this.tableComponents[5].disabled = true
          this.tableComponents[6].disabled = true
          this.tableComponents[7].disabled = true
          this.tableComponents[8].disabled = true
        } else {
          this.tableComponents[2].disabled = false
          this.tableComponents[3].disabled = false
          this.tableComponents[4].disabled = false
          this.tableComponents[5].disabled = false
          this.tableComponents[6].disabled = false
          this.tableComponents[7].disabled = false
          this.tableComponents[8].disabled = false
        }
      }
    },
    'formField.warehouseId': {
      handler(val) {
        this.$refs['multipleTable'].queryTable()
      }
    }
  },
  methods: {
    // onQueryReturn(response){
    //    this.$refs["multipleTable"].list=response
    // },
    showEdit() {
      this.editPopupsVisible = true
    },
    // 关闭弹窗
    closeEdit(type) {
      this.$emit('close', type)
    },
    deleteTable() {
      const aa = this.$refs['multipleTable'].list
      for (const i of this.selectiondata) {
        this.$refs['multipleTable'].list = aa.filter((item) => item !== i)
      }
    },
    pass() {
      request({
        url: api.checkStoreMakeStart.APIUrl,
        method: 'post',
        data: {
          checkModel: this.formField.checkModel,
          parmaList: this.selectiondata
        }
      }).then((res) => {
        this.$message.success(res.msg)
        this.popupsVisible = false
        this.$parent.queryTable(1)
      })
    },
    handFileListChange(file, fileList) {
      if (this.beforeAvatarUpload(file)) {
        this.handleChange(file)
      }
    },
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: '文件大小不能超过50M',
          type: 'warning'
        })
        return false
      }
      const fileType = file.name.substr(file.name.lastIndexOf('.') + 1)
      if (fileType != 'xls' && fileType != 'xlsx') {
        this.$message({
          message: '只能导入后缀为xls,xlsx的文件！',
          type: 'warning'
        })
        return false
      }
      return true
    },
    handleChange(param) {
      const loading = this.$loading({
        lock: true,
        text: '正在导入...',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      const that = this
      const url = api.importExcelToDlrStorage.APIUrl
      that
        .$requestUpload(url, param)
        .then((response) => {
          if (response.result === '1') {
            this.$refs['multipleTable'].list = response.rows
          } else {
            this.$message({
              message: response.msg,
              type: 'warning'
            })
          }
        })
        .catch((err) => {})
        .finally(() => {
          loading.close()
        })
    },
    templateDownload() {
      const fileName = this.$utils.fileNameWithTime('新建盘点单.xlsx')
      this.$requestAPI({
        apiUrl: api.downloadTemplateToDlrStorage.APIUrl,
        variables: { dataType: 'excel' }
      })
        .then((res) => {
          this.$utils.downloadFile(res, fileName)
        })
        .catch((err) => {
          console.log(err)
        })
    },
    exportExcel111() {
      exportExcel(
        this.formField,
        api.exportDlrStorageDetails.APIUrl,
        api.exportDlrStorageDetails.ServiceCode,
        '新建盘点单'
      )
    }
    // queryform() {
    // var queryid = { orderId: this.dataForForm.saleOrderId }
    // // 先读取参数中的传输对象
    // const returnObj = {
    // // api配置
    //   apiConfig: orgApis.orderinvoicedetailsQuery,
    // 条件/实体参数（变量），根据typeParam中的定义配置
    // variables: queryid
    // }
    // 转换了中台请求格式数据
    // var paramD = this.$getParams(returnObj, null, this.dynamicApiStyle)
    // 调用中台API方法（可复用）
    // this.$requestAPI(paramD, this.dynamicApiStyle).then(response => {
    //   if (response.result === '0') {
    //     if (response.msg) {
    //       this.$message({
    //         message: response.msg,
    //         type: 'warn',
    //         uration: 2000
    //       })
    //     }
    //     return
    //   }
    //   // 返回json
    //   if (response.result === '1') {
    //     Object.assign(this.formField, response.rows[0], response.rows[1])
    //     console.log(this.formField)
    //   }
    // }).catch(err => {
    //   console.info(err)
    // })
    // }
  }
}
</script>
<style lang='scss' scoped>
/deep/ .el-dialog {
  margin-top: 5rem !important;
}
</style>
